package com.pjj.projectservice.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.bind.annotation.ControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 76004
 * @apiNote
 * @date 2023/2/16 19:11
 */
@Component
@Aspect
public class ProjectAdvice {
    @Pointcut("execution(Object com.pjj.projectservice.controller.*.*(..))")
    void verify(){}

    @Autowired
    HttpServletRequest request;

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Around(value = "verify()")
    public Object verifyToken(ProceedingJoinPoint joinPoint) throws Throwable {
        Map<String,Object> map = new HashMap<>();
        try{
            map = (Map<String, Object>) joinPoint.proceed();
            String token = request.getHeader("token");
            String flag = redisTemplate.opsForValue().get(token);
            System.out.println("user token:"+token);
            System.out.println("redis token:"+flag);
            if(flag!=null){
                redisTemplate.opsForValue().set(token,"1",1, TimeUnit.HOURS);
            }
            else{
                map.put("code",200);
                map.put("msg","用户未登录");
            }

        }catch (Exception e){
            map.put("code",200);
            map.put("msg",e.toString());
        }
        return map;
    }
}
